<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="搜索" prop="searchKey" class="search-input-item">
            <div class="search-input-group">
              <el-input
                v-model="queryParams.searchKey"
                placeholder="请输入作者名或小说名"
                clearable
                class="search-input"
                prefix-icon="el-icon-search"
                @keyup.enter.native="handleQuery"
              />
              <el-button
                type="primary"
                icon="el-icon-search"
                class="input-search-button"
                @click="handleQuery"
              >搜索</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="性别分类" prop="gender">
            <el-radio-group v-model="queryParams.gender" @change="handleGenderChange" class="gender-group">
              <el-radio label="male">男生</el-radio>
              <el-radio label="female">女生</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="分类名称" prop="categoryName" v-if="queryParams.gender">
            <el-radio-group v-model="queryParams.categoryName" class="category-group">
              <template v-if="queryParams.gender === 'male'">
                <el-radio label="玄幻">玄幻</el-radio>
                <el-radio label="都市">都市</el-radio>
                <el-radio label="仙侠">仙侠</el-radio>
                <el-radio label="科幻">科幻</el-radio>
                <el-radio label="历史">历史</el-radio>
                <el-radio label="游戏">游戏</el-radio>
                <el-radio label="悬疑">悬疑</el-radio>
                <el-radio label="奇幻">奇幻</el-radio>
                <el-radio label="武侠">武侠</el-radio>
                <el-radio label="军事">军事</el-radio>
              </template>
              <template v-else>
                <el-radio label="古代言情">古代言情</el-radio>
                <el-radio label="现代言情">现代言情</el-radio>
                <el-radio label="仙侠奇缘">仙侠奇缘</el-radio>
                <el-radio label="玄幻言情">玄幻言情</el-radio>
                <el-radio label="浪漫青春">浪漫青春</el-radio>
                <el-radio label="快穿">快穿</el-radio>
                <el-radio label="穿书">穿书</el-radio>
                <el-radio label="重生">重生</el-radio>
                <el-radio label="甜宠">甜宠</el-radio>
                <el-radio label="豪门">豪门</el-radio>
              </template>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="queryParams.status" class="status-group">
              <el-radio :label="1">连载中</el-radio>
              <el-radio :label="2">已完结</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总字数" prop="wordCount">
            <el-input-number v-model="queryParams.wordCount" :min="0" placeholder="请输入总字数" class="word-count-input" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="search-button">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="reset-button">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-table v-loading="loading" :data="allbookList" @selection-change="handleSelectionChange" class="book-table">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="小说名" align="center" prop="title">
        <template slot-scope="scope">
          <span class="novel-title" @click="goToDetail(scope.row)">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者名字" align="center" prop="authorName" />
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="封面" align="center" prop="coverUrl">
        <template slot-scope="scope">
          <el-image 
            style="width: 50px; height: 70px" 
            :src="scope.row.coverUrl" 
            :preview-src-list="[scope.row.coverUrl]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="collection" />
      <el-table-column label="点击量" align="center" prop="clicks" />
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="pagination"
    />

    <!-- 添加或修改全部作品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="book-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小说标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入小说标题" />
        </el-form-item>
        <el-form-item label="作者ID" prop="authorId">
          <el-input v-model="form.authorId" placeholder="请输入作者ID" />
        </el-form-item>
        <el-form-item label="作者名字" prop="authorName">
          <el-input v-model="form.authorName" placeholder="请输入作者名字" />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-select v-model="form.categoryName" placeholder="请选择分类名称">
            <el-option-group label="男生分类">
              <el-option label="玄幻" value="玄幻" />
              <el-option label="都市" value="都市" />
              <el-option label="仙侠" value="仙侠" />
              <el-option label="科幻" value="科幻" />
              <el-option label="历史" value="历史" />
              <el-option label="游戏" value="游戏" />
              <el-option label="悬疑" value="悬疑" />
              <el-option label="奇幻" value="奇幻" />
              <el-option label="武侠" value="武侠" />
              <el-option label="军事" value="军事" />
            </el-option-group>
            <el-option-group label="女生分类">
              <el-option label="古代言情" value="古代言情" />
              <el-option label="现代言情" value="现代言情" />
              <el-option label="仙侠奇缘" value="仙侠奇缘" />
              <el-option label="玄幻言情" value="玄幻言情" />
              <el-option label="浪漫青春" value="浪漫青春" />
              <el-option label="快穿" value="快穿" />
              <el-option label="穿书" value="穿书" />
              <el-option label="重生" value="重生" />
              <el-option label="甜宠" value="甜宠" />
              <el-option label="豪门" value="豪门" />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="连载中" :value="1" />
            <el-option label="已完结" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="小说简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="form.coverUrl" placeholder="请输入封面URL" />
        </el-form-item>
        <el-form-item label="总字数" prop="wordCount">
          <el-input-number v-model="form.wordCount" :min="0" placeholder="请输入总字数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, getAllbook, delAllbook, addAllbook, updateAllbook, search, getNovelContent, getNovelChapter } from "@/api/allbook/allbook";

export default {
  name: "Allbook",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 全部作品表格数据
      allbookList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchKey: "",
        gender: "male",
        categoryName: "",
        status: 1,
        wordCount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "小说标题不能为空", trigger: "blur" }
        ],
        authorId: [
          { required: true, message: "作者ID不能为空", trigger: "blur" }
        ],
        authorName: [
          { required: true, message: "作者名字不能为空", trigger: "blur" }
        ],
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    // 首次进入页面时加载全部数据
    this.list();
  },
  methods: {
    /** 性别切换事件 */
    handleGenderChange() {
      this.queryParams.categoryName = "";
    },

    /** 查询全部作品列表 */
    list() {
      this.loading = true;
      const params = {
        categoryName: this.queryParams.categoryName || null,
        status: this.queryParams.status || null,
        wordCount: this.queryParams.wordCount || null
      };
      list(params).then(response => {
        this.allbookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 如果有搜索关键词，使用search接口
      if (this.queryParams.searchKey) {
        this.loading = true;
        search({
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          authNameOrNovelName: this.queryParams.searchKey
        }).then(response => {
          this.allbookList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        // 没有搜索关键词时使用普通列表查询
        const params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          categoryName: this.queryParams.categoryName || null,
          status: this.queryParams.status || null,
          wordCount: this.queryParams.wordCount || null
        };
        this.loading = true;
        list(params).then(response => {
          this.allbookList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        searchKey: "",
        gender: "male",
        categoryName: "",
        status: 1,
        wordCount: null
      };
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        authorId: null,
        authorName: null,
        categoryName: null,
        status: null,
        description: null,
        coverUrl: null,
        wordCount: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加全部作品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAllbook(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改全部作品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAllbook(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAllbook(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除全部作品编号为"' + ids + '"的数据项？').then(function() {
        return delAllbook(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('allbook/allbook/export', {
        ...this.queryParams
      }, `allbook_${new Date().getTime()}.xlsx`)
    },
    /** 跳转到详情页 */
    goToDetail(row) {
      // 先获取小说内容和章节信息
      Promise.all([
        getNovelContent(row.title),
        getNovelChapter(row.title)
      ]).then(([contentRes, chapterRes]) => {
        // 将获取到的数据存储到路由参数中
        this.$router.push({
          path: '/novel/detail',
          query: {
            title: row.title,
            content: contentRes.data,
            chapters: chapterRes.data
          }
        });
      }).catch(error => {
        this.$message.error('获取小说信息失败：' + error.message);
      });
    },
  }
};
</script>

<style scoped>
.search-form {
  background-color: #f5f7fa;
  padding: 25px;
  border-radius: 10px;
  margin-bottom: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-input-item {
  width: 100%;
  margin-bottom: 20px;
}

.search-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-input {
  flex: 1;
  margin-right: 15px;
}

.input-search-button {
  height: 48px;
  padding: 0 25px;
  font-size: 16px;
  border-radius: 24px;
  background-color: #409EFF;
  border: none;
  transition: all 0.3s;
}

.input-search-button:hover {
  background-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.search-input .el-input__inner {
  height: 48px;
  line-height: 48px;
  font-size: 16px;
  padding-left: 45px;
  border-radius: 24px;
  border: 2px solid #e4e7ed;
  transition: all 0.3s;
  background-color: #f8f9fb;
}

.search-input .el-input__inner:focus {
  border-color: #409EFF;
  background-color: #fff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.search-form .el-form-item__label {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  line-height: 40px;
}

.gender-group, .category-group, .status-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.el-radio {
  margin-right: 20px;
  margin-bottom: 10px;
  font-size: 15px;
}

.el-radio__label {
  font-size: 15px;
  padding-left: 8px;
}

.word-count-input {
  width: 100%;
}

.word-count-input .el-input__inner {
  font-size: 15px;
  height: 36px;
  line-height: 36px;
}

.search-button, .reset-button {
  margin: 0 10px;
  padding: 10px 25px;
  font-size: 15px;
}

.search-button {
  background-color: #409EFF;
}

.search-button:hover {
  background-color: #66b1ff;
}

.reset-button {
  border-color: #DCDFE6;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  margin-bottom: 10px;
}

.book-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.book-table .el-table__header th {
  background-color: #f5f7fa;
  font-size: 15px;
  font-weight: 500;
  color: #333;
  padding: 12px 0;
}

.book-table .el-table__body td {
  font-size: 14px;
  padding: 12px 0;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.book-dialog .el-dialog__body {
  padding: 20px 40px;
}

.book-dialog .el-form-item {
  margin-bottom: 22px;
}

.book-dialog .el-input, .book-dialog .el-select, .book-dialog .el-input-number {
  width: 100%;
}

.book-dialog .dialog-footer {
  text-align: center;
  padding-top: 20px;
}

.novel-title {
  color: #409EFF;
  cursor: pointer;
  transition: all 0.3s;
}

.novel-title:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>
